<template>
  <div class="goods-cate">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品列表</span>
      </div>
      <el-table :data="tableData" :style="{ width: w + 'px' }">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="商品名称">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="商品id">
                <span>{{ props.row.id }}</span>
              </el-form-item>
              <el-form-item label="所属分类">
                <span>{{ props.row.category }}</span>
              </el-form-item>
              <el-form-item label="创建时间">
                <span>{{ props.row.ctime | formatDate }}</span>
              </el-form-item>
              <el-form-item label="商品价格">
                <span>{{ props.row.price }}</span>
              </el-form-item>
              <el-form-item label="商品销量">
                <span>{{ props.row.sellCount }}</span>
              </el-form-item>
              <el-form-item label="商品图片">
                <img :src="props.row.imgUrl" alt="" />
              </el-form-item>
              <el-form-item label="商品描述">
                <span>{{ props.row.goodsDesc }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name"> </el-table-column>
        <el-table-column label="所属分类" prop="category"> </el-table-column>
        <el-table-column label="商品价格" prop="price"> </el-table-column>
        <el-table-column label="商品图片" prop="imgUrl">
          <template slot-scope="scope">
            <img :src="scope.row.imgUrl" width="50" height="50" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="商品描述" prop="goodsDesc"></el-table-column>
        <el-table-column label="操作">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editData(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="mini" @click="delBtn(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>

      <!-- 模态框 -->
      <el-dialog title="修改商品" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="商品名称" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" :label-width="formLabelWidth">
            <el-select v-model="form.category" placeholder="请选择活动区域">
              <el-option
                :label="item"
                :value="item"
                v-for="item in cateList"
                :key="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图片上传" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="action"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品描述" :label-width="formLabelWidth">
            <el-input
              v-model="form.goodsDesc"
              autocomplete="off"
              type="textarea"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="商品价格"
            prop="price"
            :label-width="formLabelWidth"
          >
            <el-input-number
              v-model="form.price"
              :precision="2"
              :step="0.1"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="savaEditBtn">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { goodsList, goodsEdit, goodsDelet } from "../../api/goods";
import { categories } from "../../api/goods";
import dayjs from "dayjs";
export default {
  data() {
    return {
      w: document.body.clientWidth - 300,
      action: "http://127.0.0.1:5000/goods/goods_img_upload",
      cateList: [], //所有分类
      currentPage: 1,
      total: 0,
      tableData: [],
      category: "",
      name: "",
      pageSize: 5,
      imgUrl: "",
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: "",
        category: "",
        goodsDesc: "",
        imgUrl: "",
        price: "",
      },
      formLabelWidth: "120px",
    };
  },
  methods: {
    //删除商品
    delBtn(id) {
      console.log(id);
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await goodsDelet({ id }); //删除账号的接口
          console.log(res);
          this.loadList();
        })
        .catch(() => {
          console.log("取消");
        });
    },
    //保存修改
    async savaEditBtn(row) {
      let res = await goodsEdit(this.form);
      console.log(res);
      this.loadList();
      this.dialogFormVisible = false;
    },
    //编辑
    async editData(row) {
      console.log(row);
      this.dialogFormVisible = true;
      // this.form = row;
      this.form = { ...row };
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.loadList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadList();
    },
    async loadList() {
      let res = await goodsList({
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        name: this.name,
        category: this.category,
      });
      console.log(res);
      let { total, data } = res;
      this.tableData = data;
      this.total = total;
    },
    handleAvatarSuccess(res) {
      this.form.imgUrl = res.imgUrl;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/webp";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //处理页面宽度发生改变的函数
    resizeHandle() {
      this.w = document.body.clientWidth - 300;
    },
  },
  async created() {
    this.loadList();
    //获取启用的所有分类
    this.cateList = await categories();
    console.log(this.cateList);
    window.addEventListener("resize", this.resizeHandle);
    this.loadList();
  },
  filters: {
    formatDate(val) {
      return dayjs(val).format("YYYY/MM/DD");
    },
  },
  beforeDestroy() {
    //注销页面发生改变大小的事件
    window.removeEventListener("resize", this.resizeHandle);
  },
};
</script>

<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.block {
  margin-top: 20px;
}

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>